var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op

/* GET types listing. */
router.get('/', async function (req, res, next) {
    try {
        var types = await models.Type.findAll()
        res.json({ types })
    } catch (e) {
        console.log(e);
    }
});

router.post('/', async function (req, res, next) {
    const { title } = JSON.parse(req.query.data)
    try {
        var type = await models.Type.create({
            title
        })
        res.json({ type })
    } catch (e) {
        console.log(e)
    }
})

// 修改部门信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { title } = JSON.parse(req.query.data)
    try {
        var type = await models.Type.update({
            title
        }, { where: { id } })

        res.json({ type })
    } catch (e) {
        console.log(e)
    }
})

// 删除部门信息
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id
    var type = await models.Type.findByPk(id)
    if (type) {
        type.destroy()
        res.json({ msg: '删除成功' })
    } else {
        res.json({ msg: '不存在该数据' })
    }
})

module.exports = router;
